package org.zhuzx.util;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import javax.validation.constraints.Pattern;

/**
 * 封装了列表查询功能中常用的若干参数，若实际业务中需要的参数与这里面的有差异，可以继承它再添加、覆盖。<br>
 * 或者单纯改写属性，比如在子类中定义同名字段并标注hidden = true，在接口文档中隐藏不需要的参数。<br>
 * 注：complexParam会自动转义百分号、下划线等特殊字符。
 * orderField可以传入驼峰格式的字段名（会自动转成下划线格式的表字段名）。
 * @author zhuzx 2022/7/4
 */
@Getter
@Setter
@ApiModel
public class QueryParam extends PageParam {

	@ApiModelProperty(value = "复合查询参数，支持模糊匹配多个字段。")
	private String complexParam;
	
	@Pattern(regexp = UnifiedConstants.REGEX_DATE_OR_DATETIME)
	@ApiModelProperty(value = "时间起始值，格式为yyyy-MM-dd HH:mm:ss，比如2022-01-01 22:22:22。<br>" +
			"若前端控件只精确到天，也可以传日期格式值yyyy-MM-dd，后台接收到入参后会自动拼接00:00:00，" +
			"以标准格式的时间值作为参数值执行查询。", position = 1001)
	private String timeStart;

	@Pattern(regexp = UnifiedConstants.REGEX_DATE_OR_DATETIME)
	@ApiModelProperty(value = "时间结束值，格式同timeStart参数。<br>" +
			"若前端传日期格式值yyyy-MM-dd，同timeStart参数类似，后台接收到入参后会自动拼接23:59:59。", position = 1002)
	private String timeEnd;
	
	@ApiModelProperty(value = "指定根据哪个字段排序，传入某一个字段名（查询接口返回的结果集中的字段）。" +
			"与orderType参数搭配使用。", position = 1003)
	private String orderField;
	
	@ApiModelProperty(value = "指定是正序还是倒序：asc正序，desc倒序。与orderField参数搭配使用。", position = 1004)
	private String orderType;

	public void setComplexParam(String complexParam) {
		this.complexParam = MicroUtil.escapeSqlParamLikeValue(complexParam);
	}

	public void setOrderField(String orderField) {
		if (GeneralUtil.isBlank(orderField)) {
			return;
		} else {
			orderField = orderField.trim();
		}
		BizAssert.mustTrue(orderField.matches("\\w+"), "orderField参数值非法：" + orderField);
		this.orderField = MicroUtil.convertCamelCasedToUnderline(orderField);
	}

	public void setOrderType(String orderType) {
		if (GeneralUtil.isBlank(orderType)) {
			return;
		} else {
			orderType = orderType.trim().toLowerCase();
		}
		BizAssert.mustTrue(orderType.equals("asc") || orderType.equals("desc"),
				"orderType参数值非法：" + orderType);
		this.orderType = orderType;
	}

	public void setTimeStart(String timeStart) {
		if (GeneralUtil.isBlank(timeStart)) {
			return;
		}
		if (timeStart.matches(UnifiedConstants.REGEX_DATE)) {
			timeStart += " 00:00:00";
		}
		this.timeStart = timeStart;
	}
	
	public void setTimeEnd(String timeEnd) {
		if (GeneralUtil.isBlank(timeEnd)) {
			return;
		}
		if (timeEnd.matches(UnifiedConstants.REGEX_DATE)) {
			timeEnd += " 23:59:59";
		}
		this.timeEnd = timeEnd;
	}
}